const gulp = require('gulp');
const ts = require('gulp-typescript');
const cls = require("gulp-clean")
const uglify = require('gulp-uglify-es').default
const es = require('event-stream')
const filter = require('gulp-filter');
const tsProject = ts.createProject('tsconfig.json');
const rename = require("gulp-rename");
function clean(cb) {
    return gulp.src(["./dist/*.*"], { allowEmpty: true })
        .pipe(cls());
}

function compile() {
    let tsResult = tsProject.src()
        .pipe(tsProject());
    return es.merge(
        tsResult.dts,
        tsResult.js.pipe(uglify()),
        gulp.src("./src/report.js").pipe(uglify()),
        gulp.src("./src/miniui.js")
    ).pipe(gulp.dest('./dist'));
};
function compile_dev_final() {
    let tsResult = tsProject.src()
        .pipe(tsProject());
    return es.merge(
        tsResult.dts,
        tsResult.js.pipe(uglify()),
        gulp.src("./src/report.js").pipe(uglify()),
        gulp.src("./src/miniui_src.js").pipe(rename("miniui.js")).pipe(uglify()),
    ).pipe(gulp.dest('./dist'));
};
function compile_dev(cb) {
    let tsResult = tsProject.src()
        .pipe(tsProject())
    return es.merge(
        tsResult,
        gulp.src("./src/report.js"),
        gulp.src("./src/miniui_src.js").pipe(rename("miniui.js"))
    ).pipe(gulp.dest("./dist"));
}

function typefile() {
    return gulp.src(["./src/miniui.d.ts"])
        .pipe(gulp.symlink('./dist', { relativeSymlinks: true }))
}
function typefile_compile() {
    return gulp.src(["./src/miniui.d.ts"])
        .pipe(gulp.dest('./dist'))
}


function locale() {
    return gulp.src("./src/locale/**/*")
        .pipe(gulp.dest("./dist/locale"))
}
function themes() {
    return gulp.src("./src/themes/**/*")
        .pipe(gulp.dest("./dist/themes"))
}
function res() {
    return gulp.src("./src/res/**/*")
        .pipe(gulp.dest("./dist/res"))
}


function packageFile(cb) {
    return es.merge(
        gulp.src("./package.json")
            .pipe(es.through(function (data) {
                let json = JSON.parse(data.contents.toString());
                delete json.scripts;
                delete json.devDependencies;
                data.contents = Buffer.from(JSON.stringify(json, null, '  '));
                this.emit('data', data);
            })),
        gulp.src("./src/miniui.css"),
        gulp.src("./README.md")
    ).pipe(gulp.dest('./dist'))
}

function watch_dev(cb) {
    gulp.watch(["./src/*.ts", "./src/report.js"], gulp.series(compile_dev));
}
function watch_Final(cb) {
    gulp.watch(["./src/*.ts", "./src/report.js"], compile);
}
exports.build = gulp.series(clean, gulp.parallel(typefile_compile, packageFile, locale, themes, res, compile));
exports.default = this.build;
exports.watch = gulp.series(clean, gulp.parallel(typefile, packageFile, locale, themes, res, compile_dev), watch_dev);
exports.watchFinal = gulp.series(clean, gulp.parallel(typefile, packageFile, locale, themes, res, compile_dev_final), watch_Final);
exports.clean = clean